const fs = require('fs');
const path = require('path');
const { createVideoFromImages } = require('./createVideo');
const imgsDir = path.join(__dirname, 'imgs');
const audioDir = path.join(__dirname, 'audio');
const outputDir = path.join(__dirname, 'dist');

// 获取文件夹下所有图片地址
function getAllImagePaths(folderPath) {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp'];
    const files = fs.readdirSync(folderPath);
    return files.filter(file => {
        const ext = path.extname(file).toLowerCase();
        return imageExtensions.includes(ext);
    }).map(file => path.join(folderPath, file));
}


function getRandomMp3Path(folderPath) {
    const files = fs.readdirSync(folderPath);
    const mp3Files = files.filter(file => path.extname(file).toLowerCase() === '.mp3');
    if (mp3Files.length === 0) {
        return null;
    }
    const randomIndex = Math.floor(Math.random() * mp3Files.length);
    return path.join(folderPath, mp3Files[randomIndex]);
}



/**
 * 从给定的图片集合中随机选取 3 张图片，如果集合元素不足 3 个，则全部返回。
 * @param {Array<string>} imgs - 图片路径集合
 * @returns {Array<string>} - 随机选取的图片路径集合
 */
function getRandomThreeImages(imgs, index) {
    // const shuffled = [...imgs];
    // let currentIndex = shuffled.length;
    // let temporaryValue, randomIndex;
    return imgs[index] || imgs[0];
    // // 打乱数组顺序
    // while (0 !== currentIndex) {
    //     randomIndex = Math.floor(Math.random() * currentIndex);
    //     currentIndex -= 1;

    //     temporaryValue = shuffled[currentIndex];
    //     shuffled[currentIndex] = shuffled[randomIndex];
    //     shuffled[randomIndex] = temporaryValue;
    // }

    // return shuffled.slice(0, max);
}

/**
 * 异步获取 dist 文件夹下的所有文件
 * @returns {Promise<Array<string>>}
 */
const getDistFiles = async () => {
    const distDir = path.join(__dirname, 'dist');
    try {
        const files = await fs.promises.readdir(distDir);
        return files.map(file => path.join(distDir, file));
    } catch (error) {
        console.error('获取 dist 文件夹下的文件时出错:', error);
        throw error;
    }
};



// ... existing code ...
function deleteDistFiles() {
    return new Promise((resolve, reject) => {
        getDistFiles().then(distFiles => {
            const deletePromises = [];
            for (const file of distFiles) {
                deletePromises.push(
                    fs.promises.unlink(file)
                        .then(() => {
                            console.log(`成功删除文件: ${file}`);
                        })
                        .catch(error => {
                            console.error(`删除文件 ${file} 时出错:`, error);
                        })
                );
            }
            Promise.all(deletePromises).then(() => {
                resolve();
            }).catch(err => {
                reject(err);
            });
        }).catch(error => {
            reject(error);
        });
    });
}

async function main(params) {
    const args = process.argv.slice(2);
    const imgMax = Number(args[1] || 1);
    console.log(imgMax, 'imgMaximgMaximgMax');

    // 是否删除
    if (args[0] === '1') {
        console.log('进来了');
        await deleteDistFiles();
    }
    const imgs = getAllImagePaths(imgsDir);
    const audio = getRandomMp3Path(audioDir);
    let cycleLength = Math.floor(imgs.length / imgMax);
    for (let index = 0; index < cycleLength; index++) {
        const threeImages = getRandomThreeImages(imgs, index);
        const output = path.join(outputDir, `${Date.now()}.mp4`);
        await createVideoFromImages([threeImages], audio, output);
    }
}

(async () => {
    await main();
})();







